package com.example.dingdong.rest;

import java.io.File;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.dingdong.FilePath;
import com.example.dingdong.daomain.MenuEntity;
import com.example.dingdong.enumerate.MenuOptionEnum;
import com.example.dingdong.service.MenuService;
import com.example.dingdong.util.CheckRequestUtil;
import com.example.dingdong.util.ExceptionType;
import com.example.dingdong.util.FileUploadUtil;
import com.example.dingdong.util.MyException;

/**
 * 
 * @ClassName: MenuRest
 * @Description: 
 * @Author :chengwenixng
 * @Copyright: Smartlab411
 * @DateTime 2022-03-24 22:42:50
 */
@RestController
@RequestMapping("/web/rest/menu/")
public class MenuRest {
	//创建日志
	private static final Logger log = LoggerFactory.getLogger(MenuRest.class);
	@Autowired
	private MenuService  menuService;
	/**
	 * 
	 * @Title: getAllMenus
	 * @Description: 
	 * @Author coding
	 * @DateTime 2022-03-24 23:10:32
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("getAllMenus")
	public JSONObject getAllMenus(@RequestBody String reqStr) {
		log.info("getAllMenus:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "getAllMenus");
		return_data.put("type", "response");
		return_data.put("response", response);
		try {
			CheckRequestUtil.checkReqInterface(reqStr, "getAllMenus");
			
			// 获取数据
			List <MenuEntity> menuEntities=  menuService.allMenuInformationData();
			JSONArray data = new JSONArray();
			
			//遍历返回数据
			for (MenuEntity menuEntity : menuEntities) {
				JSONObject addData = new JSONObject();
				addData.put("id", menuEntity.getId()); 
				addData.put("key", menuEntity.getId());
				addData.put("photoPath", menuEntity.getPhotoPath() != null ?menuEntity.getPhotoPath():""); // 图书图片
				addData.put("menuName", menuEntity.getMenuName()); 
				addData.put("dshclassification", menuEntity.getDshclassification()); 
				addData.put("isSticky", menuEntity.getIsSticky()); 
				addData.put("isRecommend", menuEntity.getIsRecommend()); 
				addData.put("price", menuEntity.getPrice()); 
				addData.put("dishDetails", menuEntity.getDishDetails()); 
				addData.put("ceckingInTime", menuEntity.getCeckingInTime()); 
				data.add(addData);
			}
			/**
			 * 返回前端数据
			 */
			response.put("res", true);
			response.put("message", data);
		}catch (MyException e) {
			log.error("getAllMenus:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("getAllMenus:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		System.out.println(response.toJSONString());
		System.out.println("getAllMenus接口方法调用完成");
		return return_data;
	}
	/**
	 * 新增菜品
	 * 
	 * @Title: addMenu
	 * @Description:
	 * @Author chengwenixng
	 * @DateTime  2021-03-21
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("addMenu")
	public JSONObject addMenu(@RequestBody String reqStr) {
		log.info("addMenu:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "addMenu");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "addMenu");
			/**
			 * 获取前端数据
			 */
			if (req.get("menuName") == null) {
				throw new MyException("缺少menuName字段！");
			}
			String menuName = req.getString("menuName");
			
			if (req.get("price") == null) {
				throw new MyException("缺少price字段！");
			}
			Double price =  req.getDouble("price");
			
			if (req.get("dishDetails") == null) {
				throw new MyException("缺少dishDetails字段！");
			}
			String dishDetails = req.getString("dishDetails");
			
			if (req.get("dshclassification") == null) {
				throw new MyException("缺少dishDetails字段！");
			}
			Boolean dshclassification= req.getBoolean("dshclassification");
			
			if (req.get("photoPath") == null) {
				throw new MyException("缺少photoPath字段！");
			}
			String photoPath = req.getString("photoPath");
			/**
			 * 根据菜品名字判断该是否已存在
			 */
			 MenuEntity menuEntity =  menuService.getfindByMenuName(menuName, true);
			if (menuEntity!= null) {
				throw new MyException("该菜单已存在！");
			}
			
			/**
			 * 新增菜品
			 */
			 MenuEntity menuEntities = new MenuEntity();
			 /**
				 * 先判断缓存文件夹里面有没有相关的图片文件
				 */
				File cachePictureFile = new File(photoPath);
				if (!cachePictureFile.exists()) {
					throw new MyException(ExceptionType.NotFound, "暂无该缓存图片，请重新上传文件后添加！");
				}
				
				/**
				 * 将缓存图片复制到相应的路径下，保存内容
				 */
				// 创建当前对象的文件夹
				String entityDir = FilePath.MENU_PATH + "/" +menuEntities.getId();
				File entityDirFile = new File(entityDir);
				if (!entityDirFile.exists()) {
					boolean flag = entityDirFile.mkdirs();
					if (!flag) {
						menuEntities.setDelFlag(false);
						menuService.savaMenuEntities(menuEntities);
						throw new MyException(ExceptionType.OperationError, "创建文件夹失败，请重新添加！");
					}
				}
				// 获取源文件名
				String[] strArr = photoPath.split("\\/");
				String sourceFileName = strArr[strArr.length - 1];
				// 新文件路径
				String picturePath = entityDir + "/" + System.currentTimeMillis() + "_" + sourceFileName;
				// 复制文件
				boolean copyFlag = FileUploadUtil.copyFile(photoPath, picturePath);
				if (!copyFlag) {
					menuEntities.setDelFlag(false);
					menuService.savaMenuEntities(menuEntities);
					throw new MyException(ExceptionType.OperationError, "复制文件失败，请重新添加！");
				}
			 menuEntities.setMenuName(menuName);
			 menuEntities.setDishDetails(dishDetails);
			 menuEntities.setPrice(price);
			 menuEntities.setPhotoPath(photoPath);
			 menuEntities.setDshclassification(dshclassification);
			menuService.savaMenuEntities(menuEntities);

			/**
			 * 返回前端数据
			 */
			response.put("res", true);
		} catch (MyException e) {
			log.error("add:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("add:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
	/**
	 * 
	 * @Title: deleteMenu
	 * @Description: 
	 * @Author coding
	 * @DateTime 2022-03-24 22:55:16
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("deleteMenu")
	public JSONObject deleteMenu(@RequestBody String reqStr) {
		log.info("deleteMenu:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject returnData = new JSONObject();
		JSONObject response = new JSONObject();
		returnData.put("cmd", "deleteMenu");
		returnData.put("type", "response");
		returnData.put("response", response);
		
		try {
			JSONObject request = CheckRequestUtil.checkReqInterface(reqStr, "deleteMenu");
			
			List<Object> idList = request.getJSONArray("idList");
			if (idList == null || idList.size() == 0) {
				throw new MyException(ExceptionType.NotFound, "请传入idList！");
			}

			/**
			 * 查找数据库中的数据
			 */
			for (Object object : idList) {
				 MenuEntity menuEntity =menuService.getMenuEntities(Long.valueOf(String.valueOf(object)).longValue(), true);
				if  ( menuEntity == null) {
					throw new MyException(ExceptionType.LookupDatabaseIsEmpty, "数据库中暂无该数据！");
				}
				/**
				 * 删除数据
				 */
				 menuEntity.setDelFlag(false);
			    menuService.savaMenuEntities( menuEntity);
			}
			
			/**
			 * 返回数据
			 */
			response.put("res", true);
		} catch (MyException e) {
			log.error("deleteMenu:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("deleteMenu:");
			e.printStackTrace();
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		log.info("deleteMenu: " + returnData);
		return returnData;
	}
	/**
	 * 编辑菜品
	 * 
	 * @Title: editMenu
	 * @Description:
	 * @Author chengwenixng
	 * @DateTime  2021-03-21
	 * @param reqStr
	 * @return
	 */
	@RequestMapping(" editMenu")
	public JSONObject  editMenu(@RequestBody String reqStr) {
		log.info("addMenu:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", " editMenu");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "editMenu");
			/**
			 * 获取前端数据
			 */
			// 获取学生id
			if (  req.get("id") == null) {
				throw new MyException("缺少id 字段！");
			}
			if (req.get("menuName") == null) {
				throw new MyException("缺少menuName字段！");
			}
			if (req.get("price") == null) {
				throw new MyException("缺少price字段！");
			}			
			if (req.get("dishDetails") == null) {
				throw new MyException("缺少dishDetails字段！");
			}			
			if (req.get("dshclassification") == null) {
				throw new MyException("缺少dishDetails字段！");
			}
			menuService.modifyMenuEntities(req);
			/**
			 * 返回前端数据
			 */
			response.put("res", true);
		} catch (MyException e) {
			log.error("editMenu:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("editMenu:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
	/**
	 * 
	 * @Title: getOption
	 * @Description: 
	 * @Author coding
	 * @DateTime 2022-03-25 01:07:44
	 * @param reqStr
	 * @return
	 */
	@RequestMapping("getOption")
	public JSONObject getOption(@RequestBody String reqStr) {
		log.info("getOption:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "getOption");
		return_data.put("type", "response");
		return_data.put("response", response);
		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "getOption");
			
			if (req.get("id") == null) {
				throw new MyException(ExceptionType.NotFound, "缺少id字段！");
			}
			if (req.get("type") == null) {
				throw new MyException(ExceptionType.NotFound, "缺少type字段！");
			}
			String type = req.getString("type");
			// 判断操作类型
			MenuOptionEnum typeEnum = MenuOptionEnum.valueOf(type);
			if (typeEnum == null) {
				throw new Exception("类型不正确");
			}
			req.put("typeId", typeEnum.ordinal());
			// 进行操作
			menuService.getOption(req);
			
			response.put("res", true);
		} catch (MyException e) {
			log.error("getOption:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("getOption:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
	@RequestMapping("addShoppingCat")
	public JSONObject addShoppingCat(@RequestBody String reqStr) {
		log.info("addShoppingCat:" + reqStr);
		/**
		 * 预返回数据
		 */
		JSONObject return_data = new JSONObject();
		JSONObject response = new JSONObject();
		return_data.put("cmd", "addShoppingCat");
		return_data.put("type", "response");
		return_data.put("response", response);

		try {
			JSONObject req = CheckRequestUtil.checkReqInterface(reqStr, "addShoppingCat");
			/**
			 * 获取前端数据
			 */
			// 获取商品id
			if (req.get("id") == null) {
				throw new MyException("缺少id字段！");
			}
			Long id = req.getLong("id");
			//图书
			if (req.get("catNumber") == null) {
				throw new MyException("缺少catNumber字段！");
			}
			Long catNumber = req.getLong("catNumber");
			
			//根据id查询商品
			 MenuEntity menuEntity =menuService.getMenuEntities(id, true);
			
			 menuEntity.setCatNumber(catNumber);
			 menuEntity.setTotalPrice(menuEntity.getPrice()*catNumber);
			 menuEntity.setIsShoppingCart(!menuEntity.getIsShoppingCart());
			 menuService.savaMenuEntities( menuEntity);

			/**
			 * 返回前端数据
			 */
			response.put("res", true);
		} catch (MyException e) {
			log.error("addShoppingCat:" + e.getReason());
			response.put("res", false);
			response.put("exception", e.getReason());
		} catch (Exception e) {
			log.error("addShoppingCat:" + e.getMessage());
			response.put("res", false);
			response.put("exception", e.getMessage());
		}
		return return_data;
	}
}
